package com.algorithm;

/**
 * 回文字符串
 */
public class LongestPalindromicSubstring {


    public static String longestPalindrome(String s) {
        int max = 0;
        byte[] bytes = s.getBytes();
        String result = "";
        //处理aba
        for (int i = 0; i < bytes.length; i++) {
            int n = 1;
            while (i - n >= 0 && i + n <= bytes.length - 1 && bytes[i - n] == bytes[i + n]) {
                n++;
            }
            if (2 * n - 1 > max) {
                max = 2 * n - 1;
                for (int i1 = i - n + 1; i1 <= i + n - 1; i1++) {
                    result = s.substring(i - n + 1, i + n);
                }
            }
        }
        //处理bb
        for (int i = 0; i < bytes.length; i++) {
            int n = 0;
            while (i - n >= 0 && i + 1 + n <= bytes.length - 1 && bytes[i - n] == bytes[i + 1 + n]) {
                n++;
            }
            if (2 * n> max) {
                max = 2 * n - 1;
                for (int i1 = i - n + 1; i1 <= i + n; i1++) {
                    result = s.substring(i - n + 1, i+1 + n);
                }
            }
        }

        return result;
    }

    public static void main(String[] args) {
//        String str = "babad";
        String str = "cbbd";
        System.out.println(longestPalindrome(str));
    }
}
